<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/19
 * Time: 12:28
 */
namespace app\badminton\controller;

use app\badminton\model\AdminGroup;
use app\badminton\model\AdminRoleGroup;
use app\badminton\model\Adminuser;
use app\badminton\model\BbsCard;
use think\Cache;
use think\Cookie;
use think\Request;

class Admin extends BassController{

    /**
     * 管理员列表
     */
    public function admin_list(){

       $admin_list = Adminuser::all();
       foreach ($admin_list as $k=>$v){
           $group_id = AdminGroup::where('uid',$v['id'])->value('group_id');
           $v['groupname'] = AdminRoleGroup::where('id',$group_id)->value('groupname');
       }
       return view('',['admin_list'=>$admin_list]);
    }


    /**
     * 管理员添加 | 修改
     */
    public function admin(){

        if(\request()->isPost()){
            $data = \request()->post();
            if(empty($data['id'])){
                $data['password'] = md5($data['password']);
                $user = Adminuser::create([
                    'username'=>$data['username'],
                    'password'=>$data['password'],
                    'create_time'=>time()
                    ]);
                $id = $user->id;
                $res = AdminGroup::create([
                    'uid'=>$id,
                    'group_id'=>$data['adminRole']
                ]);
            }else{
                $user = new Adminuser();
                $user->allowField(true)->save($data,$data['id']);
                $res = AdminGroup::where('uid',$data['id'])->update(['group_id' => $data['adminRole']]);
            }
            if($res){
                return_json(1,'操作成功');
            }else{
                return_json(0,'操作失败');
            }
        }
        //查询出有多少种角色组
        $result = AdminRoleGroup::all();
        $id = intval(Request::instance()->param('id'));
        $one = Adminuser::where('id',$id)->find();
        if(empty($one)){
            $one = null;
        }else{
            $one['group_id'] = AdminGroup::where('uid',$id)->value('group_id');
            $one['groupname'] = AdminRoleGroup::where('id',$one['group_id'])->value('groupname');
        }
        return view('',['result'=>$result,'one'=>$one]);
    }

    /**
     * 修改密码
     */
    public function pwd_edit(){
        if(\request()->isPost()){
            $data = \request()->post();
            $password = md5($data['password']);
            $user = Adminuser::get($data['id']);
            $user->password = $password;
            $res = $user->save();
            if($res){
                return_json(1,'操作成功');
            }else{
                return_json(0,'操作失败');
            }
        }
        $uid = Request::instance()->param('id');
        $one = Adminuser::where('id',$uid)->find();

        return view('',['one'=>$one]);
    }

}